package getGitProjects;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;

public class Main {

	public static void main(String[] args) throws Exception {
		//本地存储库位置
		String localPath = "F:\\projects";
		//远程git项目索引文件
		String excelPath = "C:\\Users\\admin\\Desktop\\Test\\待爬取的数据.xlsx";
		//获取需要下载的项目和地址
		Map<String, String> maps = getProjectUrl(excelPath);
		List<String> list = getLoadedProjects(localPath);
		maps = getNewProjectUrl(maps,list);
		//开始下载
		downloadProjects(maps,localPath);
	}
	
	//批量下载远程项目
	public static void downloadProjects(Map<String, String> maps,String localPath) {
		for(String filename:maps.keySet()) {
			String url = maps.get(filename);
			String newLocalPath = localPath + File.separator + filename;
			if(cloneRepository(url,newLocalPath)) System.out.println(String.format("项目：%s 下载成功！", filename));
			else System.out.println(String.format("项目：%s 下载失败，地址：%s", filename, url));
		}
	}
	
	//项目去重
	public static Map<String,String> getNewProjectUrl(Map<String, String> maps,List<String> list){
		Map<String,String> newMaps = new HashMap<>();
		for (String key : maps.keySet()) {
			//本地中不含该项目，则需要下载
			if(!list.contains(key)) newMaps.put(key, maps.get(key));
		}
		return newMaps;
	}

	//下载远程git项目
	public static boolean cloneRepository(String url, String localPath) {
		try {
			CloneCommand cc = Git.cloneRepository().setURI(url);
			cc.setDirectory(new File(localPath)).call();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	//获取本地已经下载的项目名
	public static List<String> getLoadedProjects(String localPath) {
		List<String> list = new ArrayList<String>();
		File file = new File(localPath);
        File[] filesName = file.listFiles();
        for (File file2 : filesName) {
			if(file2.isDirectory()) {
				if(file2.listFiles().length > 1) list.add(file2.getName());
				else deleteDir(file2);
			}
		}
        return list;
	}
	
	//删除空目录（包含隐藏.git的目录）
	public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir
                (new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        if(dir.delete()) return true;
        else return false;
    }

	//获取所有需要下载的项目地址
	public static Map<String, String> getProjectUrl(String excelPath) throws Exception {
		File file = new File(excelPath);
		if (!file.exists()) {
			throw new Exception("文件不存在!");
		}
		Map<String, String> maps = new HashMap<>();
		InputStream in = new FileInputStream(file);
		// 读取整个Excel
		XSSFWorkbook sheets = new XSSFWorkbook(in);
		// 获取第一个表单Sheet
		XSSFSheet sheetAt = sheets.getSheetAt(0);
		// 默认第一行为标题行，i = 0
		XSSFRow titleRow = sheetAt.getRow(0);
		// 循环获取每一行数据
		for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
			XSSFRow row = sheetAt.getRow(i);
			// 读取每一格内容
			String getFileName = row.getCell(1).getStringCellValue();
			String getURL = row.getCell(2).getStringCellValue();
			maps.put(getFileName, getURL);
		}
		return maps;
	}
}
